package com.macro.mall.portal.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.macro.mall.mapper.OmsOrderMapper;
import com.macro.mall.mapper.PmsCommentMapper;
import com.macro.mall.mapper.PmsProductMapper;
import com.macro.mall.model.*;
import com.macro.mall.portal.domain.PmsCommentDetail;
import com.macro.mall.portal.service.PmsCommentService;
import com.macro.mall.portal.service.UmsMemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品评价管理Service实现类
 */
@Service
public class PmsCommentServiceImpl implements PmsCommentService {
    @Autowired
    private PmsCommentMapper commentMapper;
    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private OmsOrderMapper orderMapper;

    @Override
    public int create(PmsComment comment) {
        // 设置评价用户信息
        UmsMember currentMember = memberService.getCurrentMember();
        comment.setMemberId(currentMember.getId());
        comment.setMemberNickName(currentMember.getNickname());
        comment.setMemberIcon(currentMember.getIcon());
        comment.setMemberIp(request.getRemoteAddr());
        comment.setCreateTime(new Date());
        // 初始化数据
        comment.setShowStatus(1);  // 默认显示
        comment.setReadCount(0);   // 阅读数
        comment.setCollectCouont(0); // 收藏数
        comment.setReplayCount(0); // 回复数
        int count = commentMapper.insert(comment);
        
        // 更新订单评论时间
        if (count > 0 && comment.getOrderId() != null) {
            OmsOrder order = new OmsOrder();
            order.setId(comment.getOrderId());
            order.setCommentTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
        }
        
        return count;
    }

    @Override
    public List<PmsComment> list(Long productId, Integer star, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        PmsCommentExample example = new PmsCommentExample();
        example.setOrderByClause("create_time desc");
        PmsCommentExample.Criteria criteria = example.createCriteria();
        criteria.andShowStatusEqualTo(1); // 只查询显示的评价
        if (productId != null) {
            criteria.andProductIdEqualTo(productId);
        }
        if (star != null) {
            criteria.andStarEqualTo(star);
        }
        return commentMapper.selectByExample(example);
    }
    
    @Override
    public Map<String, Object> listProductComments(Long productId, Integer star, Integer pageSize, Integer pageNum) {
        Map<String, Object> result = new HashMap<>();
        
        // 尝试获取当前登录用户
        UmsMember currentMember = null;
        try {
            currentMember = memberService.getCurrentMember();
        } catch (Exception e) {
            // 未登录状态，不处理异常
        }
        
        // 当前是否登录，未登录时设置为false
        result.put("isLogin", currentMember != null);
        
        // 查询所有评价
        // 根据star参数查询不同星级的评价
        List<PmsComment> allComments = new ArrayList<>();
        
        if (star == 0) {
            // 不过滤星级
            PageHelper.startPage(pageNum, pageSize);
            PmsCommentExample allExample = new PmsCommentExample();
            allExample.setOrderByClause("create_time desc");
            PmsCommentExample.Criteria allCriteria = allExample.createCriteria();
            allCriteria.andProductIdEqualTo(productId);
            allCriteria.andShowStatusEqualTo(1);
            allComments = commentMapper.selectByExample(allExample);
        } else if (star == 5) {
            // 查询5星评价
            PageHelper.startPage(pageNum, pageSize);
            PmsCommentExample allExample = new PmsCommentExample();
            allExample.setOrderByClause("create_time desc");
            PmsCommentExample.Criteria allCriteria = allExample.createCriteria();
            allCriteria.andProductIdEqualTo(productId);
            allCriteria.andShowStatusEqualTo(1);
            allCriteria.andStarEqualTo(5);
            allComments = commentMapper.selectByExample(allExample);
        } else if (star == 3) {
            // 查询3-4星评价
            // 使用两次查询并合并结果
            PageHelper.startPage(pageNum, pageSize);
            PmsCommentExample example3 = new PmsCommentExample();
            example3.setOrderByClause("create_time desc");
            PmsCommentExample.Criteria criteria3 = example3.createCriteria();
            criteria3.andProductIdEqualTo(productId);
            criteria3.andShowStatusEqualTo(1);
            criteria3.andStarEqualTo(3);
            List<PmsComment> comments3 = commentMapper.selectByExample(example3);
            
            PageHelper.startPage(pageNum, pageSize);
            PmsCommentExample example4 = new PmsCommentExample();
            example4.setOrderByClause("create_time desc");
            PmsCommentExample.Criteria criteria4 = example4.createCriteria();
            criteria4.andProductIdEqualTo(productId);
            criteria4.andShowStatusEqualTo(1);
            criteria4.andStarEqualTo(4);
            List<PmsComment> comments4 = commentMapper.selectByExample(example4);
            
            allComments.addAll(comments3);
            allComments.addAll(comments4);
            
            // 手动分页和排序
            int totalSize = allComments.size();
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, totalSize);
            
            // 按创建时间降序排序
            allComments.sort((c1, c2) -> c2.getCreateTime().compareTo(c1.getCreateTime()));
            
            if (startIndex < totalSize) {
                allComments = allComments.subList(startIndex, endIndex);
            } else {
                allComments = new ArrayList<>();
            }
        } else if (star == 1) {
            // 查询1-2星评价
            // 使用两次查询并合并结果
            PageHelper.startPage(pageNum, pageSize);
            PmsCommentExample example1 = new PmsCommentExample();
            example1.setOrderByClause("create_time desc");
            PmsCommentExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andProductIdEqualTo(productId);
            criteria1.andShowStatusEqualTo(1);
            criteria1.andStarEqualTo(1);
            List<PmsComment> comments1 = commentMapper.selectByExample(example1);
            
            PageHelper.startPage(pageNum, pageSize);
            PmsCommentExample example2 = new PmsCommentExample();
            example2.setOrderByClause("create_time desc");
            PmsCommentExample.Criteria criteria2 = example2.createCriteria();
            criteria2.andProductIdEqualTo(productId);
            criteria2.andShowStatusEqualTo(1);
            criteria2.andStarEqualTo(2);
            List<PmsComment> comments2 = commentMapper.selectByExample(example2);
            
            allComments.addAll(comments1);
            allComments.addAll(comments2);
            
            // 手动分页和排序
            int totalSize = allComments.size();
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, totalSize);
            
            // 按创建时间降序排序
            allComments.sort((c1, c2) -> c2.getCreateTime().compareTo(c1.getCreateTime()));
            
            if (startIndex < totalSize) {
                allComments = allComments.subList(startIndex, endIndex);
            } else {
                allComments = new ArrayList<>();
            }
        }
        
        // 分离我的评价和其他评价
        List<PmsComment> myComments = new ArrayList<>();
        List<PmsComment> otherComments = new ArrayList<>();
        
        if (currentMember != null && !CollectionUtils.isEmpty(allComments)) {
            // 已登录用户，分离我的评价和其他用户的评价
            Long memberId = currentMember.getId();
            for (PmsComment comment : allComments) {
                if (memberId.equals(comment.getMemberId())) {
                    myComments.add(comment);
                } else {
                    otherComments.add(comment);
                }
            }
        } else {
            // 未登录时，所有评价都是其他用户的评价
            otherComments.addAll(allComments);
        }
        
        // 分页信息
        PageInfo<PmsComment> pageInfo = new PageInfo<>(allComments);
        result.put("pageInfo", pageInfo);
        result.put("myComments", myComments);
        result.put("otherComments", otherComments);
        
        return result;
    }
    
    @Override
    public List<PmsCommentDetail> listMemberComments(Integer pageSize, Integer pageNum) {
        UmsMember currentMember = memberService.getCurrentMember();
        PageHelper.startPage(pageNum, pageSize);
        PmsCommentExample example = new PmsCommentExample();
        example.setOrderByClause("create_time desc");
        PmsCommentExample.Criteria criteria = example.createCriteria();
        criteria.andMemberIdEqualTo(currentMember.getId());
        List<PmsComment> commentList = commentMapper.selectByExample(example);
        
        // 转换为详情对象
        List<PmsCommentDetail> detailList = new ArrayList<>();
        for (PmsComment comment : commentList) {
            detailList.add(convertToDetail(comment));
        }
        return detailList;
    }
    
    @Override
    public PmsCommentDetail getCommentDetail(Long id) {
        PmsComment comment = commentMapper.selectByPrimaryKey(id);
        if (comment == null) {
            return null;
        }
        return convertToDetail(comment);
    }
    
    /**
     * 将评价转换为包含商品和订单信息的详情
     */
    private PmsCommentDetail convertToDetail(PmsComment comment) {
        PmsCommentDetail detail = new PmsCommentDetail();
        BeanUtils.copyProperties(comment, detail);
        
        // 获取商品信息
        if (comment.getProductId() != null) {
            PmsProduct product = productMapper.selectByPrimaryKey(comment.getProductId());
            detail.setProduct(product);
        }
        
        // 获取订单信息
        if (comment.getOrderId() != null) {
            OmsOrder order = orderMapper.selectByPrimaryKey(comment.getOrderId());
            detail.setOrder(order);
        }
        
        return detail;
    }

    @Override
    public PmsComment getItem(Long id) {
        return commentMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateShowStatus(List<Long> ids, Integer showStatus) {
        if (CollectionUtils.isEmpty(ids)) {
            return 0;
        }
        PmsComment record = new PmsComment();
        record.setShowStatus(showStatus);
        PmsCommentExample example = new PmsCommentExample();
        example.createCriteria().andIdIn(ids);
        return commentMapper.updateByExampleSelective(record, example);
    }

    @Override
    public int delete(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return 0;
        }
        PmsCommentExample example = new PmsCommentExample();
        example.createCriteria().andIdIn(ids);
        return commentMapper.deleteByExample(example);
    }

    @Override
    public int createReply(Long commentId, String content) {
        // 查询评价信息
        PmsComment comment = commentMapper.selectByPrimaryKey(commentId);
        if (comment == null) {
            return 0;
        }
        // 增加回复数
        comment.setReplayCount(comment.getReplayCount() + 1);
        commentMapper.updateByPrimaryKey(comment);
        
        // 这里应该创建评价回复记录，但需要新建一个 PmsCommentReply 表和对应的实体类
        // 简化处理，直接返回1表示回复成功
        return 1;
    }

    @Override
    public Map<String, Object> commentStatistics(Long productId) {
        Map<String, Object> result = new HashMap<>();
        
        // 查询该商品的所有显示评价
        PmsCommentExample example = new PmsCommentExample();
        example.createCriteria().andProductIdEqualTo(productId).andShowStatusEqualTo(1);
        List<PmsComment> allComments = commentMapper.selectByExample(example);
        
        // 统计总评价数
        int totalCount = allComments.size();
        result.put("totalCount", totalCount);
        
        // 按星级统计
        int goodCount = 0;  // 好评：5星
        int mediumCount = 0;  // 中评：3-4星
        int badCount = 0;  // 差评：1-2星
        
        for (PmsComment comment : allComments) {
            Integer star = comment.getStar();
            if (star == null) continue;
            
            if (star == 5) {
                goodCount++;
            } else if (star == 4 || star == 3) {
                mediumCount++;
            } else if (star == 2 || star == 1) {
                badCount++;
            }
        }
        
        result.put("goodCount", goodCount);
        result.put("mediumCount", mediumCount);
        result.put("badCount", badCount);
        
        // 计算好评率
        BigDecimal goodRate = BigDecimal.ZERO;
        if (totalCount > 0) {
            goodRate = new BigDecimal(goodCount).divide(new BigDecimal(totalCount), 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
        }
        result.put("goodRate", goodRate);
        
        // 尝试获取当前登录用户
        UmsMember currentMember = null;
        try {
            currentMember = memberService.getCurrentMember();
        } catch (Exception e) {
            // 未登录状态，不处理异常
        }
        
        // 当前是否登录，未登录时设置为false
        result.put("isLogin", currentMember != null);
        
        return result;
    }
} 